package javamobile.billsplit;

import java.io.IOException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*; 

import javamobile.utils.MySocket;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class CreateBillActivity extends Activity {
	public static final String PREFS_NAME = "MyPrefsFile";
	
	
	private ImageButton take_photo_button; 
	private ImageButton add_photo_button; 
	private ImageButton add_audio_button; 
	private Button add_more_button; 
	private Button send; 
	private Button get_location;
	private TableLayout splitTable; 
    
    private String username; 
    private EditText payer;
    private EditText amount;
    private EditText date;
    private EditText description;
    private EditText splitNameTemp;
    private EditText splitAmtTemp; 
    private EditText location;
    private TextView addAudio;
    private ImageView image;
    private int ways = 0; 
    
    View.OnClickListener takePhotoHandler = new View.OnClickListener() {
    	@Override
    	public void onClick(View v) {
    		startActivity(new Intent(CreateBillActivity.this, TakePhotoActivity.class));   
    	}
    }; 
    
    View.OnClickListener addPhotoHandler = new View.OnClickListener() {
    	@Override
    	public void onClick(View v) {
    		startActivity(new Intent(CreateBillActivity.this, AddPhotoActivity.class));   
    	}
    }; 
    
    
    View.OnClickListener addAudioHandler = new View.OnClickListener() {
    	public void onClick(View v) {
    		startActivity(new Intent(CreateBillActivity.this, AddAudioActivity.class)); 

    	}
    }; 
    
    View.OnClickListener addMoreHandler = new View.OnClickListener() {
    	public void onClick(View v) {
    		// Increase number of people
    		ways++; 
    		splitTable = (TableLayout) findViewById(R.id.split_table_CREATEBILL);
            EditText splitName = new EditText(CreateBillActivity.this);
            EditText splitAmt = new EditText(CreateBillActivity.this);
            //Button splitCancel = new Button(CreateBillActivity.this); 
            TableRow tr = new TableRow(CreateBillActivity.this);
            tr.setLayoutParams(new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT));
            tr.addView(splitName);
            tr.addView(splitAmt);
            splitTable.addView(tr);
    	}
    };
    
    /*
    View.OnClickListener eraseHandler = new View.OnClickListener() {
    	public void onClick(View v) {
    		// Erase number of people
    		ways--; 
    	}
    };
    */
    
    @SuppressLint("SimpleDateFormat")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_bill); 
        // Buttons 
        take_photo_button = (ImageButton) findViewById(R.id.take_photo_btn_CREATEBILL); 
        add_photo_button = (ImageButton) findViewById(R.id.add_photo_btn_CREATEBILL);
        add_audio_button = (ImageButton) findViewById(R.id.add_audio_btn_CREATEBILL); 
        add_more_button = (Button) findViewById(R.id.add_more_btn_CREATEBILL);
        send = (Button) findViewById(R.id.send_btn_CREATEBILL); 
        get_location = (Button) findViewById(R.id.Get_Location_CREATEBILL);
        location = (EditText) findViewById(R.id.Location_CREATEBILL);
        image = (ImageView) findViewById(R.id.image_CREATEBILL);
        addAudio = (TextView) findViewById(R.id.add_Audio_CREATEBILL);
        
        take_photo_button.setOnClickListener(takePhotoHandler); 
        add_photo_button.setOnClickListener(addPhotoHandler); 
        add_audio_button.setOnClickListener(addAudioHandler);  
        add_more_button.setOnClickListener(addMoreHandler); 
        
        // Shared preference and username 
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        username = settings.getString("username", "DEFAULT");
        
        // Text fields 
        payer = (EditText) findViewById(R.id.paid_by_text_CREATEBILL);
        amount = (EditText) findViewById(R.id.total_amt_text_CREATEBILL);
        date = (EditText) findViewById(R.id.date_text_CREATEBILL);
        description = (EditText) findViewById(R.id.descipt_text_CREATEBILL);
        
        // Dynamic field TABLE
        
        send.setOnClickListener(new OnClickListener(){
        	@SuppressWarnings({ "unchecked", "unused" })
			public void onClick(View v){
	        	Intent toPending = new Intent(CreateBillActivity.this, PendingBillsActivity.class);
	        	Map<String, Object> input = new HashMap<String, Object>();
	            
	        	// Get input text 
	        	String payerStr = payer.getText().toString();
	        	String amountStr = amount.getText().toString();
	        	String dateStr = date.getText().toString();
	        	String descriptionStr = description.getText().toString();
	        	String locationStr = location.getText().toString();
	        	
	        	// CHECK FOR ERRORS / MISSING FIELDS
	        	ArrayList<String> input_errors = new ArrayList<String>(); 
	        	if(descriptionStr.isEmpty()){
	        		input_errors.add("\"Description\" is Missing");			
	     		}
	     		if(payerStr.isEmpty()){
	     			input_errors.add("\"Paid by\" is Missing");	
	     		}
	            Double amountDou = 0.0; 
	        	try{
	        		amountDou = Double.parseDouble(amountStr);
	        	} catch (NumberFormatException nfe){
	        		input_errors.add("\"Total Amount\" must be doubles");	
	        	}
	        	Date d;
				DateFormat df = new SimpleDateFormat ("MM/dd/yyyy");
				try {
					d = df.parse(dateStr);
				} catch (ParseException e) {
					input_errors.add("\"Date\" must be in MM/dd/yyyy format");	
				}
	        	
	            // CHECK MORE PEOPLE TABLE 
	        	List<String> emailsList = new ArrayList<String>();
	        	List<Double> amountsList = new ArrayList<Double>();
	        	Double sum = 0.0;
	            for(int i=1;i<ways+1; i++){
	            	// Get people from each row
	            	TableRow row = (TableRow) splitTable.getChildAt(i);
	            	splitNameTemp = (EditText) row.getChildAt(0);
	            	splitAmtTemp = (EditText) row.getChildAt(1);
	            	
	            	String splitNameStr = splitNameTemp.getText().toString(); 
	            	String splitAmtStr = splitAmtTemp.getText().toString(); 
	            	
	            	//Enter into lists 
	 
	            	if(splitNameStr.isEmpty() || splitAmtStr.isEmpty()){
	            		input_errors.add("Name field/Amounts is missing");
	            	}
	            	else {
	            		emailsList.add(splitNameStr);
	            	
		            	Double splitAmtDou = 0.0; 
		            	try{
		            		splitAmtDou = Double.parseDouble(splitAmtStr);
		            		amountsList.add(splitAmtDou);
		            		sum += splitAmtDou;
		            	}
		            	catch (NumberFormatException nfe){
		            		input_errors.add("\"Split Amounts\" must all be doubles");
		            	}
	            	}
	            }
	            
	            if (sum > amountDou) {
	            	input_errors.add("Total amount must be greater than the sum of the split amounts");
	            }
	            
	            // If nobody is added 
	            if(ways == 0){
	            	input_errors.add("You need to add at least one person");
	            }
	        	
	            // SEND ERROR REPORT FOR INPUT 
	            if(input_errors.size() !=0){
	            	Intent toError = new Intent(CreateBillActivity.this, ErrorActivity.class);
	            	toError.putStringArrayListExtra("errorlist", input_errors);
	            	startActivity(toError);
	            }
	            // Only send things to server if no error in create bill form 
	            else{
		            // SERVER STUFF  
		            input.put("username", username);
		     		input.put("payer", payerStr);
		    		input.put("amount", amountDou);
		     		input.put("date", dateStr);
		     		input.put("description", descriptionStr);
		     		input.put("emails", emailsList);
		     		input.put("amounts", amountsList);
		     		input.put("location", locationStr);
		     		input.put("ways", ways);
		     		
		     		input.put("action", "create.do");
		        	
		     		// CHECK FOR ERROR IN SERVER STUFF 
		     		try {
		    			Map<String, Object> output = MySocket.runSocket(input);
		        	    List<String> errors = (List<String>) output.get("errors");
		        	    if (errors.size()==0) {
		        	    	startActivity(toPending);	// Return to pending bills when done
		        	    	finish();
		        	    }
		        	    else {
		        	    	Intent toError = new Intent(CreateBillActivity.this, ErrorActivity.class);
		        	    	toError.putStringArrayListExtra("errorlist", new ArrayList<String>(errors));
		        	    	startActivity(toError);
		        	    }
					} catch (UnknownHostException e) {
						System.out.println("UnknownHostException");
						e.printStackTrace();
					} catch (IOException e) {
						System.out.println("IOException");
						e.printStackTrace();
					} catch (ClassNotFoundException e) {
						System.out.println("ClassNotFoundException");
						e.printStackTrace();
					}        	
	            }
        	}
        });
        
        get_location.setOnClickListener(new OnClickListener(){
    		public void onClick(View v){
        		Intent toLocation = new Intent(CreateBillActivity.this, LocationActivity.class);
        		startActivity(toLocation);
        	}
        });
    
    }
    

    
    @Override
    public void onResume() {
    	super.onResume();
    	SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        String loc_Str = settings.getString("location", "Unavaliable");
        location.setText(loc_Str);

        String galaryPath = settings.getString("galary", "NULL");
        if (!galaryPath.equals("NULL"))
        	image.setImageBitmap(BitmapFactory.decodeFile(galaryPath));
        
        String soundPath = settings.getString("sound", "NULL");
        if (!soundPath.equals("NULL"))
        	addAudio.setText("Audio recorded at "+soundPath);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true; 
    }





}